#include "PrecompiledHeaders.h"
#include "ScoreObjectControl.h"
#include "FromString.h"

ScoreObjectControl::ScoreObjectControl()
{
    score_objects = std::map<OgreNewt::Body *, ScoreObjectData>();
}

ScoreObjectControl *ScoreObjectControl::clone()
{
    ScoreObjectControl *soc = new ScoreObjectControl();
    std::map<OgreNewt::Body *, ScoreObjectData>::iterator it;
    for (it = score_objects.begin(); it != score_objects.end(); it++) {
        ScoreObjectData d = it->second;
        soc->score_objects[it->first] = d;
    }
    return soc;
}

void ScoreObjectControl::reset()
{
    std::map<OgreNewt::Body *, ScoreObjectData>::iterator it;
    for (it = score_objects.begin(); it != score_objects.end(); it++) {
        if (it->second.done) {
            it->second.done = false;
            Ogre::SceneNode *node = dynamic_cast<Ogre::SceneNode*>(it->first->getOgreNode());
            if (node) node->setVisible(true);
            delete it->first->getCollision();
            it->first->setCollision(it->second.original_collision);
        }
    }
}

void ScoreObjectControl::addScoreObject(OgreNewt::Body *body, std::map<Ogre::String, Ogre::String> &params)
{
    body->setUserData(this);
    
    ScoreObjectData data;
    data.original_collision = body->getCollision();
    data.done = false;
    
    std::map<Ogre::String, Ogre::String>::iterator it;
    it = params.find("score_amount");
    if (it != params.end())
        from_string<int>( data.score_amount, it->second.c_str(), std::dec);
    else
        data.score_amount = SO_DEFAULT_SCORE;
    
    score_objects[body] = data;
}

void ScoreObjectControl::collision(OgreNewt::Body *object)
{
    std::map<OgreNewt::Body *, ScoreObjectData>::iterator it;
    it = score_objects.find(object);
    if (it != score_objects.end())
    {
        if (! it->second.done) {
            it->second.done = true;
            object->setCollision(new OgreNewt::CollisionPrimitives::Null(object->getWorld()));
            Ogre::SceneNode *node = dynamic_cast<Ogre::SceneNode*>(object->getOgreNode());
            if (node) node->setVisible(false);
            player->getSession()->addScore(it->second.score_amount);
            
            if (player->isMainPlayer())
                play_state->updateScoreOverlay();
        }
    }
}
